package com.lontyu.jsoup.job;

import com.lontyu.jsoup.entity.Book;
import com.lontyu.jsoup.service.IBookService;
import com.lontyu.jsoup.utils.JSoupUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author: xzj
 * @Dscription：
 * @Date: Created by 17:50 2018/9/13
 */
@Component
public class PullJdSitePageJob {

    @Value("${craw.site-url}")
    private String url;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    IBookService bookService;

    /**
     * 每天早上八点拉取一次数据 (目前只拉取第一页的数据，如果需要拉取其他页数据，替换page=? 参数，京东页码： 1 ，3 ，5 ...)
     *    http://search.jd.com/Search?keyword=Python&enc=utf-8&qrst=1&rt=1&stop=1&book=y&vt=2&wq=Python&page=1
     */
    @Scheduled(cron = "0 0 8 * * ?")
    public void pullData(){
        ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
        if(entity.getStatusCode()== HttpStatus.OK){
            String html = entity.getBody();
            List<Book> books = JSoupUtil.parseHtml(html);
            boolean sign = bookService.batchInsertBooks(books);
            System.out.println("拉取数据入库完成!");
        }else{
            System.out.println("拉取数据入库失败,错误信息：" + entity.getBody());
        }
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
